<?php

namespace app\admin\model\litestore;

use think\Model;
use think\Db;

class Litestoregoods extends Model
{
    // 表名
    protected $name = 'litestore_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'spec_type_text',
        'deduct_stock_type_text',
        'goods_status_text',
        'is_delete_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['goods_sort' => $row[$pk]]);
        });

        
    }

    
    public function getSpecTypeList()
    {
        return ['10' => __('Spec_type 10'),'20' => __('Spec_type 20')];
    }     


    public function getIsZhekouTypeList()
    {
        return ['0' => __('否'),'1' => __('是')];
    }    

    public function getDeductStockTypeList()
    {
        return ['10' => __('Deduct_stock_type 10'),'20' => __('Deduct_stock_type 20')];
    }     

    public function getGoodsStatusList()
    {
        return ['10' => __('Goods_status 10'),'20' => __('Goods_status 20')];
    }     

    public function getIsDeleteList()
    {
        return ['0' => __('Is_delete 0'),'1' => __('Is_delete 1')];
    }    
    public function getIsTuijianList()
    {
        return ['0' => __('不推荐'),'1' => __('推荐')];
    }

    public function getHomeList()
    {
        return ['0' => __('不推荐'),'1' => __('热销产品'),'2' => __('新品上架'),'3' => __('最近降价'),'4' => __('特价专区')];
    }     



    public function getSpecTypeTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['spec_type']) ? $data['spec_type'] : '');
        $list = $this->getSpecTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDeductStockTypeTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['deduct_stock_type']) ? $data['deduct_stock_type'] : '');
        $list = $this->getDeductStockTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getGoodsStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['goods_status']) ? $data['goods_status'] : '');
        $list = $this->getGoodsStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsDeleteTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['is_delete']) ? $data['is_delete'] : '');
        $list = $this->getIsDeleteList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function category()
    {
        return $this->belongsTo('litestorecategory', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function freight()
    {
        return $this->belongsTo('Litestorefreight', 'delivery_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

     public function shangjia()
    {
        return $this->belongsTo('app\admin\model\pifa\Shangjia', 'shangjia_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
     public function gongyingshang()
    {
        return $this->belongsTo('app\admin\model\pifa\Gongyingshang', 'gongyingshang_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联商品规格表
     */
    public function spec()
    {
        return $this->hasMany('Litestoregoodsspec','goods_id','goods_id');
    }

    /**
     * 关联商品规格关系表
     */
    public function specRel()
    {
        return $this->belongsToMany('Litestorespecvalue', 'litestore_goods_spec_rel','spec_value_id','goods_id');
    }

    /**
     * 计算显示销量 (初始销量 + 实际销量)
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getGoodsSalesAttr($value, $data)
    {
        return $data['sales_initial'] + $data['sales_actual'];
    }

    /**
     * 添加商品规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
    public function addGoodsSpec(&$data,$params,$specparams,$isUpdate = false)
    {
        // 更新模式: 先删除所有规格
        $model = new Litestoregoodsspec;

     

     

       
       


    
        // 添加规格数据
        if ($data['spec_type'] === '10') {
            // 单规格
             $isUpdate && $model->removeAll($this['goods_id']);

             if (empty($specparams['daoqi'])) {
                 $specparams['daoqi'] = date('Y-m-d', strtotime('+12 months'));
             }
            $this->spec()->save($specparams,true);
 
        } else if ($data['spec_type'] === '20') {
            // 添加商品与规格关系记录

            // $model = new Litestoregoodsspecrel;
            // $model->where('goods_id','=', $this['goods_id'])->delete();


         
            foreach ($params['spec_list'] as $key => $value) {
                $params['spec_list'][$key]['form']['baojia'] = [];
                $params['spec_list'][$key]['form']['xiangou'] = [];
                $params['spec_list'][$key]['form']['dinghuo'] = [];
                $params['spec_list'][$key]['form']['baojia_quyu'] = [];
               if (isset($params['baojia_list'][$key])) {
                  $params['spec_list'][$key]['form']['baojia'] = $params['baojia_list'][$key]['user_group'];
                  $params['spec_list'][$key]['form']['xiangou'] = $params['baojia_list'][$key]['xiangou'];
                  $params['spec_list'][$key]['form']['dinghuo'] = $params['baojia_list'][$key]['dinghuo'];
               }
               if (isset($params['shangjia_list'][$key])) {
                  $params['spec_list'][$key]['form']['baojia_quyu'] = $params['shangjia_list'][$key]['user_group'];
               }
               $params['spec_list'][$key]['form']['baojia'] = json_encode($params['spec_list'][$key]['form']['baojia']);
               $params['spec_list'][$key]['form']['xiangou'] = json_encode($params['spec_list'][$key]['form']['xiangou']);
               $params['spec_list'][$key]['form']['dinghuo'] = json_encode($params['spec_list'][$key]['form']['dinghuo']);
               $params['spec_list'][$key]['form']['baojia_quyu'] = json_encode($params['spec_list'][$key]['form']['baojia_quyu']);
            }

            
          

            $model->addGoodsSpecRel($this['goods_id'],$params['spec_attr']);
            // 添加商品sku
            

            // var_dump($params['spec_list']);
            $model->addSkuList($this['goods_id'],$params['spec_list']);
        }



    }

    public function removesku(){
        // 删除商品sku
        (new Litestoregoodsspec)->removeAll($this['goods_id']);
    }
    /**
     * 获取规格信息
     */
    // public function getManySpecData($spec_rel, $skuData)
    // {
    //     // spec_attr
    //     $specAttrData = [];
    //     foreach ($spec_rel as $item) {
    //         if (!isset($specAttrData[$item['spec_id']])) {
    //             $specAttrData[$item['spec_id']] = [
    //                 'group_id' => $item['spec']['id'],
    //                 'group_name' => $item['spec']['spec_name'],
    //                 'spec_items' => [],
    //             ];
    //         }
    //         $specAttrData[$item['spec_id']]['spec_items'][] = [
    //             'item_id' => $item['pivot']['spec_value_id'],
    //             'spec_value' => $item['spec_value'],
    //         ];
    //     }

    //     // spec_list
    //     $specListData = [];
    //     foreach ($skuData as $item) {
    //         $specListData[] = [
    //             'goods_spec_id' => $item['goods_spec_id'],
    //             'spec_sku_id' => $item['spec_sku_id'],
    //             'goods_sku_id_arr' => explode('_',$item['spec_sku_id']),
    //             'rows' => [],
    //             'form' => [
    //                 'goods_spec_id' => $item['goods_spec_id'],
    //                 'goods_no' => $item['goods_no'],
    //                 'goods_price' => $item['goods_price'],
    //                 'goods_price4' => $item['goods_price4'],
    //                 'danwei' => $item['danwei'],
    //                 'fenyong' => $item['fenyong'],
    //                 'qudao_fenyong' => $item['qudao_fenyong'],
    //                 'goods_weight' => $item['goods_weight'],
    //                 'line_price' => $item['line_price'],
    //                 'stock_num' => $item['stock_num'],
    //                 'spec_image' => $item['spec_image'],
    //             ],
    //         ];
    //     }
    //     return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
    // }


        public function getManySpecData($spec_rel, $skuData)
{
    // 1. 收集所有规格值对应的库存
    $stockMap = [];

    foreach ($skuData as $item) {
        $specValueIds = explode('_', $item['spec_sku_id']);
        foreach ($specValueIds as $specValueId) {
            if (!isset($stockMap[$specValueId])) {
                $stockMap[$specValueId] = [];
            }
            $stockMap[$specValueId][] = (int)$item['stock_num'];
        }
    }

    // 2. spec_attr 构建，同时判断 disabled 状态
    $specAttrData = [];
    foreach ($spec_rel as $item) {
        $specId = $item['spec_id'];
        $specValueId = $item['pivot']['spec_value_id'];

        if (!isset($specAttrData[$specId])) {
            $specAttrData[$specId] = [
                'group_id' => $item['spec']['id'],
                'group_name' => $item['spec']['spec_name'],
                'spec_items' => [],
            ];
        }

        // 判断 disabled: 所有关联库存都 <= 0
        $stockArr = $stockMap[$specValueId] ?? [];
        $isDisabled = empty($stockArr) || array_reduce($stockArr, function ($carry, $stock) {
            return $carry && ($stock <= 0);
        }, true);

        $specAttrData[$specId]['spec_items'][] = [
            'item_id' => $specValueId,
            'spec_value' => $item['spec_value'],
            'disabled' => $isDisabled,
        ];
    }

    // 3. spec_list 构建
    $specListData = [];
    foreach ($skuData as $item) {
        $specListData[] = [
            'goods_spec_id' => $item['goods_spec_id'],
            'spec_sku_id' => $item['spec_sku_id'],
            'goods_sku_id_arr' => explode('_', $item['spec_sku_id']),
            'rows' => [],
            'form' => [
                'goods_spec_id' => $item['goods_spec_id'],
                'goods_no' => $item['goods_no'],
                'goods_price' => $item['goods_price'],
                'goods_price2' => $item['goods_price2'],
                'danwei' => $item['danwei'],
                'goods_price4' => $item['goods_price4'],
                'daoqi' => $item['daoqi'],
                'goods_weight' => $item['goods_weight'],
                'fenyong' => $item['fenyong'],
                'qudao_fenyong' => $item['qudao_fenyong'],
                'line_price' => $item['line_price'],
                'stock_num' => $item['stock_num'],
                'baojia' => !empty($item['baojia']) ? json_decode($item['baojia'],true) : [],
                'xiangou' => !empty($item['xiangou']) ? json_decode($item['xiangou'],true) : [],
                'dinghuo' => !empty($item['dinghuo']) ? json_decode($item['dinghuo'],true) : [],
                'baojia_quyu' => !empty($item['baojia_quyu']) ? json_decode($item['baojia_quyu'],true) : [],
            ],
        ];
    }

    return [
        'spec_attr' => array_values($specAttrData),
        'spec_list' => $specListData
    ];
}

}
